<!--
 * @Author: Betty
 * @Date: 2021-02-08 22:24:21
 * @LastEditors: Betty
 * @LastEditTime: 2021-02-08 22:50:39
 * @Description: 模态框组件
-->
<template>
  <teleport to="#modal">
    <!-- 注意加上d-block的class让模态框存在时可见 -->
    <div class="modal d-block" tabindex="-1" v-if="visible">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">{{title}}</h5>
            <button type="button" class="btn-close" @click.prevent="onClose" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <slot></slot>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal" @click.prevent="onClose">{{cancelText}}</button>
            <button type="button" class="btn btn-primary" @click.prevent="onConfirm">{{confirmText}}</button>
          </div>
        </div>
      </div>
    </div>
  </teleport>
</template>

<script lang='ts'>
import { defineComponent } from 'vue'
import useDOMCreate from '../hooks/useDOMCreate'
export default defineComponent({
  name: '',
  props: {
    // 模态框标题
    title: String,
    // 控制模态框是否可见
    visible: {
      type: Boolean,
      default: false
    },
    // 取消按钮和确定按钮的文本
    cancelText: {
      type: String,
      default: '取消'
    },
    confirmText: {
      type: String,
      default: '确定'
    }
  },
  // 自定义事件有取消按钮和确定按钮被点击的事件
  emits: ['modal-on-close', 'modal-on-confirm'],
  setup(props, context) {
    // 创建modal元素，作为渲染的父节点
    useDOMCreate('modal')
    // 监听取消按钮的点击
    const onClose = () => {
      context.emit('modal-on-close')
    }
    // 监听确定按钮的点击
    const onConfirm = () => {
      context.emit('modal-on-confirm')
    }
    return {
       onClose,
       onConfirm
    }
  }
})
</script>

<style>
</style>
